package com.ulic.customerManApplication.membermodule.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.ulic.customerManApplication.constant.CONSTANT;
import com.ulic.customerManApplication.exception.SystemException;
import com.ulic.customerManApplication.journeylovemodule.bo.JourneyOfLoveActivity;
import com.ulic.customerManApplication.memberenjoymodule.bo.MemberEnjoyActivity;
import com.ulic.customerManApplication.memberenjoymodule.service.MemberEnjoyService;
import com.ulic.customerManApplication.membermodule.bo.Member;
import com.ulic.customerManApplication.membermodule.bo.SubMember;
import com.ulic.customerManApplication.membermodule.service.MemberExtService;
import com.ulic.customerManApplication.membermodule.vo.ImportVerifyVO;
import com.ulic.customerManApplication.membermodule.vo.SubMemberVO;
import com.ulic.customerManApplication.pager.PagerModel;
import com.ulic.customerManApplication.usermodule.bo.User;
import com.ulic.customerManApplication.util.config.ConfigInfo;
import com.ulic.customerManApplication.util.excel.UploadFile;

@Component("subMemberExtAction")
@Scope("prototype")
public class SubMemberExtAction extends SubMemberAction {
	private static final long serialVersionUID = 1L;

	private String memberEnjoyId;
	
	private MemberExtService memberExtService;
	private MemberEnjoyService memberEnjoyService;
	
	public static final String KEY_TOVERIFY_SUBMEMBER_LIST = "toVerifySubMemberList";
	public static final String KEY_VERIFY_SEQUENCE = "verifySequence";

	private Map<Integer, Integer> sameMemberMap;


	private List<ImportVerifyVO> verifyVOs = new ArrayList<ImportVerifyVO>();
	// 随机生成的序列，表示在session中保存的数据位当前页面操作的数据，用于反正开启多个页面来导入数据是发生的数据错乱
	private String verifySequence;
	



	public Map<Integer, Integer> getSameMemberMap() {
		return sameMemberMap;
	}

	public void setSameMemberMap(Map<Integer, Integer> sameMemberMap) {
		this.sameMemberMap = sameMemberMap;
	}

	public List<ImportVerifyVO> getVerifyVOs() {
		return verifyVOs;
	}

	public void setVerifyVOs(List<ImportVerifyVO> verifyVOs) {
		this.verifyVOs = verifyVOs;
	}


	public String getVerifySequence() {
		return verifySequence;
	}

	public void setVerifySequence(String verifySequence) {
		this.verifySequence = verifySequence;
	}

	public String getMemberEnjoyId() {
		return memberEnjoyId;
	}

	public void setMemberEnjoyId(String memberEnjoyId) {
		this.memberEnjoyId = memberEnjoyId;
	}
	

	public MemberExtService getMemberExtService() {
		return memberExtService;
	}

	@Resource
	public void setMemberExtService(MemberExtService memberExtService) {
		this.memberExtService = memberExtService;
	}

	public MemberEnjoyService getMemberEnjoyService() {
		return memberEnjoyService;
	}
	@Resource
	public void setMemberEnjoyService(MemberEnjoyService memberEnjoyService) {
		this.memberEnjoyService = memberEnjoyService;
	}

	@Override
	public String searchSubMembers() {
		if(isJourneyOfLovePage()){
			return super.searchSubMembers();
		}else{
			return searchMESubMembers();
		}
	}
	
	@Override
	public String toSaveSubMember() throws Exception {
		if(isJourneyOfLovePage()){
			return super.toSaveSubMember();
		}else{
			return toSaveMESubMember();
		}
	}
	
	@Override
	public String saveSubMember() throws Exception {
		if(isJourneyOfLovePage()){
			return super.saveSubMember();
		}else{
			return saveMESubMember();
		}
	}
	
	
	@Override
	public String updatedSubMember() throws Exception {
	 User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
	 SubMember preUpdateSubMember =getSubMemberService().getSubMember(getSubMember().getSub_id());
	 SubMember subMember = getSubMember();
	 subMember.setSub_memberType(getMemberType(subMember.getSub_donateStuNum()));
	 //是否修改捐助学生数来判断是否更新会员和爱心活动
	 if(!preUpdateSubMember.getSub_donateStuNum().equals(subMember.getSub_donateStuNum())){
		 if(preUpdateSubMember.getMember() != null){
			 Member member = getMemberService().getMember(preUpdateSubMember.getMember().getId());
			 member.setDonateStuNum(member.getDonateStuNum() - preUpdateSubMember.getSub_donateStuNum() + getSubMember().getSub_donateStuNum());
			 member.setMemberType(getMemberType(member.getDonateStuNum()));
			 getMemberService().modifyMember(member);
		 }
		 if(preUpdateSubMember.getSub_journeyOfLoveActivity() != null && !preUpdateSubMember.equals(subMember.getSub_memberType())){
			 JourneyOfLoveActivity journeyLove = getJourneyLoveService().getJourneyLoveById(preUpdateSubMember.getSub_journeyOfLoveActivity().getId());
			 if ("绿卡会员".equals(preUpdateSubMember.getSub_memberType())) {
				 journeyLove.setGreenCardMember(journeyLove.getGreenCardMember() - 1);
			 } else if ("银卡会员".equals(preUpdateSubMember.getSub_memberType())) {
				 journeyLove.setSilverCardMember(journeyLove.getSilverCardMember() - 1);
			 } else if ("金卡会员".equals(preUpdateSubMember.getSub_memberType())) {
				 journeyLove.setGoldenCardMember(journeyLove.getGoldenCardMember() - 1);
			 } else if ("金箔卡会员".equals(preUpdateSubMember.getSub_memberType())) {
				 journeyLove.setPlatinumCardMember(journeyLove.getPlatinumCardMember() - 1);
			 } else if ("钻石卡会员".equals(preUpdateSubMember.getSub_memberType())) {
				 journeyLove.setDiamondCardMember(journeyLove.getDiamondCardMember() - 1);
			 }
			 if ("绿卡会员".equals(subMember.getSub_memberType())) {
				 journeyLove.setGreenCardMember(journeyLove.getGreenCardMember() + 1);
			 } else if ("银卡会员".equals(subMember.getSub_memberType())) {
				 journeyLove.setSilverCardMember(journeyLove.getSilverCardMember() + 1);
			 } else if ("金卡会员".equals(subMember.getSub_memberType())) {
				 journeyLove.setGoldenCardMember(journeyLove.getGoldenCardMember() + 1);
			 } else if ("金箔卡会员".equals(subMember.getSub_memberType())) {
				 journeyLove.setPlatinumCardMember(journeyLove.getPlatinumCardMember() + 1);
			 } else if ("钻石卡会员".equals(subMember.getSub_memberType())) {
				 journeyLove.setDiamondCardMember(journeyLove.getDiamondCardMember() + 1);
			 }
			 getJourneyLoveService().modifyJourneyLove(journeyLove);
		 }
	 }
	 preUpdateSubMember.setSub_user(user);
	 preUpdateSubMember.setSub_birthday(subMember.getSub_birthday());
	 preUpdateSubMember.setSub_carBrand(subMember.getSub_carBrand());
	 preUpdateSubMember.setSub_memberName(subMember.getSub_memberName());
	 preUpdateSubMember.setSub_gender(subMember.getSub_gender());
	 preUpdateSubMember.setSub_idCard(subMember.getSub_idCard());
	 preUpdateSubMember.setSub_cellPhone(subMember.getSub_cellPhone());
	 preUpdateSubMember.setSub_email(subMember.getSub_email());
	 preUpdateSubMember.setSub_donateRecord(subMember.getSub_donateRecord());
	 preUpdateSubMember.setSub_forumPosting(subMember.getSub_forumPosting());
	 preUpdateSubMember.setSub_remark(subMember.getSub_remark());
	 preUpdateSubMember.setSub_reproduceIntroduce(subMember.getSub_reproduceIntroduce());
	 preUpdateSubMember.setSubCity(subMember.getSubCity());
	 preUpdateSubMember.setSubCityName(subMember.getSubCityName());
	 preUpdateSubMember.setSubCompany(subMember.getSubCompany());
	 preUpdateSubMember.setSubComName(subMember.getSubComName());
	 getSubMemberService().modifySubMember(preUpdateSubMember);
	 return SUCCESS;
}

	@Override
	public String deleteSubMember() throws Exception {
		//TODO 同一事务
		SubMember subMember = getSubMemberService().getSubMember(getSubMember().getSub_id());
		getSubMemberService().removeSubMember(subMember);
		Member member = null;
		if(subMember.getMember() != null){
			member = getMemberService().getMember(subMember.getMember().getId());
		}
		if(member!=null){
			member.setDonateStuNum(member.getDonateStuNum()-subMember.getSub_donateStuNum());
			if(member.getDonateStuNum()<0){
				member.setDonateStuNum(0);
			}
			member.setMemberType(getMemberType(member.getDonateStuNum()));
			getMemberService().modifyMember(member);
			List<SubMember> oldSubMembers = memberExtService.getSubMembersByMember(member.getId());
			for (SubMember sMember : oldSubMembers) {
				sMember.setSub_memberType(member.getMemberType());
				getSubMemberService().modifySubMember(sMember);
			}
		}
		//更新专项活动
		if(subMember.getSub_journeyOfLoveActivity() != null){
			JourneyOfLoveActivity journeyLove = getJourneyLoveService().getJourneyLoveById(subMember.getSub_journeyOfLoveActivity().getId());
			if("绿卡会员".equals(subMember.getSub_memberType())) {
				journeyLove.setGreenCardMember(journeyLove.getGreenCardMember()-1);
			}else if("银卡会员".equals(subMember.getSub_memberType())){
				journeyLove.setSilverCardMember(journeyLove.getSilverCardMember()-1);
			}else if("金卡会员".equals(subMember.getSub_memberType())){
				journeyLove.setGoldenCardMember(journeyLove.getGoldenCardMember()-1);
			}else if("金箔卡会员".equals(subMember.getSub_memberType())){
				journeyLove.setPlatinumCardMember(journeyLove.getPlatinumCardMember()-1);
			}else if("钻石卡会员".equals(subMember.getSub_memberType())){
				journeyLove.setDiamondCardMember(journeyLove.getDiamondCardMember()-1);
			}
			journeyLove.setDonateStuNum(journeyLove.getDonateStuNum()-subMember.getSub_donateStuNum());
			if(journeyLove.getGreenCardMember()<0){
				journeyLove.setGreenCardMember(0);
			}
			if(journeyLove.getSilverCardMember()<0){
				journeyLove.setSilverCardMember(0);
			}
			if(journeyLove.getGoldenCardMember()<0){
				journeyLove.setGoldenCardMember(0);
			}
			if(journeyLove.getPlatinumCardMember()<0){
				journeyLove.setPlatinumCardMember(0);
			}
			if(journeyLove.getDiamondCardMember()<0){
				journeyLove.setDiamondCardMember(0);
			}
			if(journeyLove.getDonateStuNum()<0){
				journeyLove.setDonateStuNum(0);
			}
			getJourneyLoveService().modifyJourneyLove(journeyLove);
		}
		recache();
		return SUCCESS;
	}
	@Override
	public String impSubMembers() throws Exception {
		if (getFileName() != null && getFileName().length() != 0) {
			try {
				setFileName(UploadFile.upload(getMembersFile(), getFileName(), System.currentTimeMillis()));// 先将文件上传到服务器
				List<SubMember> subMembers = analyzeData(new File(ConfigInfo.getPropertiesValue("uploadfile.path") + "/" + getFileName()));
				// 手机号码
				Set<String> phoneSet = new HashSet<String>();
				// 身份证号
				Set<String> idCardSet = new HashSet<String>();
				// 姓名
				Set<String> nameSet = new HashSet<String>();
				for (int i = 0; i < subMembers.size(); i++) {
					SubMember s = subMembers.get(i);
					if (StringUtils.isNotBlank(s.getSub_cellPhone())) {
						phoneSet.add(s.getSub_cellPhone());
					}
					if (StringUtils.isNotBlank(s.getSub_idCard())) {
						idCardSet.add(s.getSub_idCard());
					}
					nameSet.add(s.getSub_memberName());
				}
				Map<String, List<Member>> oldPhoneMembers = memberExtService.getMembersByPhone(phoneSet);
				Map<String, List<Member>> oldIdCardMembers = memberExtService.getMembersByIdCard(idCardSet);
				Map<String, List<Member>> oldNameMembers = memberExtService.getMembersByName(nameSet);
				// 库里有重复的手机号码或身份证号进行手动验证
				if (oldPhoneMembers.size() > 0 || oldIdCardMembers.size() > 0
						|| oldNameMembers.size() > 0) {
					// 将SubMember 转换为ImportVerifyVO
					for (int i = 0; i < subMembers.size(); i++) {
						SubMember s = subMembers.get(i);
						ImportVerifyVO verifyVO = new ImportVerifyVO();
						verifyVO.setSubMember(s);
						verifyVO.setIndex(i);
						List<Member> allMaySameMembers = new ArrayList<Member>();
						if (oldPhoneMembers.get(s.getSub_cellPhone()) != null) {
							allMaySameMembers.addAll(oldPhoneMembers.get(s.getSub_cellPhone()));
						}
						if (oldIdCardMembers.get(s.getSub_idCard()) != null) {
							allMaySameMembers.addAll(oldIdCardMembers.get(s.getSub_idCard()));
						}
						if (oldNameMembers.get(s.getSub_memberName()) != null) {
							allMaySameMembers.addAll(oldNameMembers.get(s.getSub_memberName()));
						}
						// 去除重复项
						List<Member> singleSameMembers = new ArrayList<Member>();
						for (Member m : allMaySameMembers) {
							boolean contains = false;
							for (Member sm : singleSameMembers) {
								if (sm.getId() == m.getId()) {
									contains = true;
									break;
								}
							}
							if (!contains) {
								singleSameMembers.add(m);
							}
						}
						verifyVO.setMaySameMembers(singleSameMembers);
						verifyVOs.add(verifyVO);
					}

					// 将要验证的数据保存在session中
					session.put(KEY_TOVERIFY_SUBMEMBER_LIST, subMembers);
					verifySequence = UUID.randomUUID().toString();
					session.put(KEY_VERIFY_SEQUENCE, verifySequence);
					return "verify";
				} else {
					saveData(subMembers, null);
					request.put("impMsg" , "导入成功!导入数据" + subMembers.size() + "条\n");
					session.put("impDataInfo",("导入成功!导入数据" + subMembers.size() + "条\n"));
				}
			} catch (SystemException e) {
				request.put("impMsg" , e.getMessage());
				session.put("impDataInfo" ,(e.getMessage()));
			}
		}
		return SUCCESS;
	}
	
	public String verifySubMembers() throws Exception {
		if (StringUtils.equals((String) session.get(KEY_VERIFY_SEQUENCE),verifySequence) && session.get(KEY_TOVERIFY_SUBMEMBER_LIST) != null) {
			List<SubMember> subMembers = (List<SubMember>) session.get(KEY_TOVERIFY_SUBMEMBER_LIST);
			saveData(subMembers, sameMemberMap);
			request.put("impMsg" , ("导入成功!导入数据" + subMembers.size() + "条\n"));
			session.put("impDataInfo" , ("导入成功!导入数据" + subMembers.size() + "条\n"));
		} else {
			request.put("impMsg" , "数据已经过期");
			session.put("impDataInfo" ,  ("数据已经过期"));
		}
		return SUCCESS;
	}

	/**
	 * 保存数据
	 * 
	 * @param subMembers
	 * @throws SystemException
	 */
	private void saveData(List<SubMember> subMembers,
			Map<Integer, Integer> sameMemberIdMap) throws SystemException {
		Map<Integer, Member> memberIndexMap = new HashMap<Integer, Member>();
		if (sameMemberIdMap != null) {
			Map<Integer, Member> memberIdMap = new HashMap<Integer, Member>();
			memberIdMap = memberExtService.getMembersById(sameMemberIdMap.values());
			for (Map.Entry<Integer, Integer> e : sameMemberIdMap.entrySet()) {
				// 传进来的ID要保证在库里全部能找到对应的会员
				if (memberIdMap.get(e.getValue()) == null) {
					throw new SystemException("数据错误!");
				}
				memberIndexMap.put(e.getKey(), memberIdMap.get(e.getValue()));
			}
		}

		// 要保存和更新的会员，如果在库有相同的则更新原来的会员，如果没有则新增新的会员
		List<Member> saveOrUpdateMemberList = new ArrayList<Member>();
		for (int i = 0; i < subMembers.size(); i++) {
			SubMember subMember = subMembers.get(i);
			Member member = null;
			// 库里有需要合并的会员
			if (memberIndexMap.containsKey(i)) {
				member = memberIndexMap.get(i);
				member.setDonateStuNum(member.getDonateStuNum() + subMember.getSub_donateStuNum());
				member.setMemberType(getMemberType(member.getDonateStuNum()));
				subMember.setSub_memberType(member.getMemberType());
			} else {
				member = new Member();
				member.setCreateDate(subMember.getSub_createDate());
				member.setUser(subMember.getSub_user());
				member.setDonateStuNum(subMember.getSub_donateStuNum());
				member.setMemberType(getMemberType(member.getDonateStuNum()));
				subMember.setSub_memberType(member.getMemberType());
			}
			subMember.setMember(member);

			if (StringUtils.isNotBlank(subMember.getSub_birthday())) {
				member.setBirthday(subMember.getSub_birthday());
			}
			if (StringUtils.isNotBlank(subMember.getSub_carBrand())) {
				member.setCarBrand(subMember.getSub_carBrand());
			}
			if (StringUtils.isNotBlank(subMember.getSub_carType())) {
				member.setCarType(subMember.getSub_carType());
			}
			member.setCellPhone(subMember.getSub_cellPhone());
			if (StringUtils.isNotBlank(subMember.getSub_donateRecord())) {
				if (StringUtils.isNotBlank(member.getDonateRecord())) {
					member.setDonateRecord(member.getDonateRecord() + "\n" + subMember.getSub_donateRecord());
				} else {
					member.setDonateRecord(subMember.getSub_donateRecord());
				}
			}
			if (StringUtils.isNotBlank(subMember.getSub_email())) {
				member.setEmail(subMember.getSub_email());
			}
			if (StringUtils.isNotBlank(subMember.getSub_forumPosting())) {
				if (StringUtils.isNotBlank(member.getForumPosting())) {
					member.setForumPosting(member.getForumPosting() + "\n" + subMember.getSub_forumPosting());
				} else {
					member.setForumPosting(subMember.getSub_forumPosting());
				}
			}
			member.setGender(subMember.getSub_gender());
			if (StringUtils.isNotBlank(subMember.getSub_idCard())) {
				member.setIdCard(subMember.getSub_idCard());
			}
			if (StringUtils.isNotBlank(subMember.getSub_reproduceIntroduce())) {
				if (StringUtils.isNotBlank(member.getReproduceIntroduce())) {
					member.setReproduceIntroduce(member.getReproduceIntroduce() + "\n" + subMember.getSub_reproduceIntroduce());
				} else {
					member.setReproduceIntroduce(subMember.getSub_reproduceIntroduce());
				}
			}
			if (StringUtils.isNotBlank(subMember.getSub_remark())) {
				if (StringUtils.isNotBlank(member.getRemark())) {
					member.setRemark(member.getRemark() + "\n" + subMember.getSub_remark());
				} else {
					member.setRemark(subMember.getSub_remark());
				}
			}

			member.setMemberName(subMember.getSub_memberName());
			member.setSubCompany(subMember.getSubCompany());
			member.setSubCity(subMember.getSubCity());
			member.setSubComName(subMember.getSubComName());
			member.setSubCityName(subMember.getSubCityName());

			saveOrUpdateMemberList.add(member);
		}

		memberExtService.saveOrUpdateMembers(saveOrUpdateMemberList);
		memberExtService.saveSubMembers(subMembers);

	}

	/**
	 * 读取Excel数据，解析为SubMember 并检验数据输入的合法性
	 * 
	 * @param file
	 * @return
	 * @throws SystemException
	 */
	private List<SubMember> analyzeData(File file) throws SystemException {
		List<SubMember> subMembers = new ArrayList<SubMember>();
		StringBuilder msg = new StringBuilder();

		// 读取Excel
		HSSFSheet sheet = null;
		try {
			FileInputStream is = new FileInputStream(file); // 读取服务器上的文件
			HSSFWorkbook wbs = new HSSFWorkbook(is);
			sheet = wbs.getSheetAt(0);
		} catch (IOException e) {
			throw new SystemException("读取文件错误");
		}
		// 获取Excel中的数据
		// --------------------------
		List<Map<Integer, String>> datas = new ArrayList<Map<Integer, String>>();
		for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
			HSSFRow row = sheet.getRow(rowIndex);
			if (null != row) {
				Map<Integer, String> rowData = new HashMap<Integer, String>();
				for (int colIndex = 0; colIndex < 13; colIndex++) {
					String value = "";
					HSSFCell cell = row.getCell((short) colIndex);
					// getValue
					if (null != cell) {
						switch (cell.getCellType()) {
						case HSSFCell.CELL_TYPE_NUMERIC: // 数字
							value = String.valueOf(cell.getNumericCellValue());
							break;
						case HSSFCell.CELL_TYPE_STRING: // 字符串
							value = cell.getStringCellValue();
							break;
						case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
							value = String.valueOf(cell.getBooleanCellValue());
							break;
						case HSSFCell.CELL_TYPE_FORMULA: // 公式
							value = cell.getCellFormula();
							break;
						case HSSFCell.CELL_TYPE_BLANK: // 空值
							value = "";
							break;
						case HSSFCell.CELL_TYPE_ERROR: // 故障
							value = "";
							break;
						default:
							value = "";
						}
					} else {
						value = "";
					}
					rowData.put(colIndex, value);
				}
				datas.add(rowData);
			} else {
				throw new SystemException("第" + (rowIndex + 1) + "行数据有误！");
			}
		}
		// --------------------------

		// 解析数据-------------------
		JourneyOfLoveActivity journeyOfLoveActivity = null;
		MemberEnjoyActivity memberEnjoyActivity = null;
		if (isJourneyOfLovePage()) {
			journeyOfLoveActivity = getJourneyLoveService().getJourneyLoveById(Integer.parseInt(getJourneyLoveId()));
		} else {
			memberEnjoyActivity = memberEnjoyService.findMemberEnjoyActivity(Integer.parseInt(memberEnjoyId));
		}
		User user = (User) session.get(CONSTANT.USER_SESSION_KEY);

		// 用于检测手机号码是否重复
		Map<String, Integer> phoneMap = new HashMap<String, Integer>();
		// 检测身份证号是否重复
		Map<String, Integer> idCardMap = new HashMap<String, Integer>();
		// 解析数据
		SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd");
		for (int rowIndex = 0; rowIndex < datas.size(); rowIndex++) {

			Map<Integer, String> data = datas.get(rowIndex);
			final SubMember subMember = new SubMember();
			subMembers.add(subMember);
			// 第A列 名称
			String memberName = data.get(0);
			if (StringUtils.isBlank(memberName)) {
				msg.append("A" + (rowIndex + 2) + "数据有误:会员姓名为空\n");
			}
			subMember.setSub_memberName(memberName);
			// 第B列性别
			String gender = data.get(1);
			if (StringUtils.isBlank(gender)) {
				msg.append("B" + (rowIndex + 2) + "数据有误:会员性别为空\n");
			}
			subMember.setSub_gender(gender);
			// 第C列身份证号
			String idCard = data.get(2);
			if (StringUtils.isNotBlank(idCard) && idCardMap.containsKey(idCard)) {
				msg.append("C" + (rowIndex + 2) + "数据有误:身份证号与C" + (idCardMap.get(idCard) + 2) + "重复");
			} else {
				idCardMap.put(idCard, rowIndex);
			}
			subMember.setSub_idCard(idCard);
			// 第D列生日
			String birthday = data.get(3);
			if (StringUtils.isNotBlank(birthday) && checkBirthday(birthday)) {
				try {
					birthday = dataFormat.format(dataFormat.parse(birthday));
				} catch (ParseException e) {
					msg.append("D" + (rowIndex + 2) + "数据有误:会员出生日期格式错误，日期格式为yyyy-MM-dd\n");
				}
			} else if (StringUtils.isNotBlank(birthday)) {
				birthday = "";
				msg.append("D" + (rowIndex + 2) + "数据有误:会员出生日期格式错误，日期格式为yyyy-MM-dd\n");
			}
			subMember.setSub_birthday(birthday);
			// 第E列手机号码
			// 第F列 上级手机号码
			String cellPhone = data.get(4);
			String parentPhone = data.get(5);
			// 两个手机号码不能同时为空
			if (StringUtils.isBlank(cellPhone) && StringUtils.isBlank(parentPhone)) {
				msg.append("第" + (rowIndex + 2) + "行数据有误:手机号码(E" + (rowIndex + 2) + ")和附属手机号码(F" + (rowIndex + 2) + ")至少填一个");
			} else {
				if (StringUtils.isNotBlank(cellPhone)) {
					if (!checkPhone(cellPhone)) {
						msg.append("E" + (rowIndex + 2) + "数据有误:会员手机号码格式错误\n");
					} else {
						if (phoneMap.containsKey(cellPhone)) {
							msg.append("E" + (rowIndex + 2) + "数据有误:会员手机号码与E" + (phoneMap.get(cellPhone) + 2) + "重复\n");
						} else {
							phoneMap.put(cellPhone, rowIndex);
						}
					}
				}
				if (StringUtils.isNotBlank(parentPhone)) {
					if (!checkPhone(parentPhone)) {
						msg.append("F" + (rowIndex + 2) + "数据有误:附属手机号码格式错误\n");
					} else {
						SubMember parentMember = new SubMember();
						parentMember.setSub_cellPhone(parentPhone);
						subMember.setParentMember(parentMember);
					}
				}
			}
			subMember.setSub_cellPhone(cellPhone);
			// 第G列邮箱
			String email = data.get(6);
			if (StringUtils.isNotBlank(email) && !checkEmail(email)) {
				email = "";
				msg.append("G" + (rowIndex + 2) + "数据有误:会员电子邮件格式错误\n");
			}
			subMember.setSub_email(email);
			// 第H列车辆品牌
			String carBrand = data.get(7);
			subMember.setSub_carBrand(carBrand);
			// 第I列车辆类型
			String carType = data.get(8);
			subMember.setSub_carType(carType);
			// 第J列捐助学生数
			String donateStuStr = data.get(9);
			int donateStuNum = 0;
			try {
				if (StringUtils.isBlank(donateStuStr)) {
					donateStuNum = 0;
				} else if (!checkSub_donateStuNum(String.valueOf(Double.valueOf(donateStuStr).intValue()))) {
					msg.append("J" + (rowIndex + 2) + "数据有误:会员捐赠学生数量格式错误，必须为0或正整数\n");
				} else {
					donateStuNum = Double.valueOf(donateStuStr).intValue();
				}
			} catch (Exception e) {
				msg.append("J" + (rowIndex + 2) + "数据有误:会员捐赠学生数量格式错误，必须为0或正整数\n");
			}
			subMember.setSub_donateStuNum(donateStuNum);
			// 第K列捐赠记录
			String donateRecord = data.get(10);
			subMember.setSub_donateRecord(donateRecord);
			// 第L转介绍记录
			String reproduceIntroduce = data.get(11);
			subMember.setSub_reproduceIntroduce(reproduceIntroduce);
			// 第M列发帖记录
			String forumPosting = data.get(12);
			subMember.setSub_forumPosting(forumPosting);
			// 第N列备注
			String remark = data.get(13);
			subMember.setSub_remark(remark);

			// 设置上额外的信息
			subMember.setSub_createDate(new Date());
			subMember.setSub_memberType(getMemberType(subMember
					.getSub_donateStuNum()));
			subMember.setSub_user(user);
			if (isJourneyOfLovePage()) {
				subMember.setSub_journeyOfLoveActivity(journeyOfLoveActivity);
				// 根据爱心之旅的分公司和中支，设置活动产生会员的分公司和中支
				subMember.setSubCompany(journeyOfLoveActivity.getSubCompany());
				subMember.setSubCity(journeyOfLoveActivity.getSubCity());
				subMember.setSubComName(journeyOfLoveActivity.getSubComName());
				subMember.setSubCityName(journeyOfLoveActivity.getSubCityName());
			} else {
				subMember.setSub_memberEnjoyActivity(memberEnjoyActivity);
				// 根据会员专项活动的分公司和中支，设置活动产生会员的分公司和中支
				subMember.setSubCompany(memberEnjoyActivity.getSubCompany());
				subMember.setSubCity(memberEnjoyActivity.getSubCity());
				subMember.setSubComName(memberEnjoyActivity.getSubComName());
				subMember.setSubCityName(memberEnjoyActivity.getSubCityName());
			}

		}
		for (int i = 0; i < subMembers.size(); i++) {
			SubMember s = subMembers.get(i);
			if (s.getParentMember() != null) {
				if (!phoneMap.containsKey(s.getParentMember().getSub_cellPhone())) {
					msg.append("F" + (i + 2) + "数据有误:在会员手机号码里找不到该附属手机号码\n");
				}
			}
		}
		// 解析数据-------------------

		if (msg.length() > 0) {
			throw new SystemException(msg.toString());
		}

		return subMembers;
	}
	
	
	public String deleteMESubMember() throws Exception{
		SubMember subMember = getSubMemberService().getSubMember(getSubMember().getSub_id());
		getSubMemberService().removeSubMember(subMember);
		Member member = getMemberService().getMember(subMember.getMember().getId());
		if(member!=null){
			member.setDonateStuNum(member.getDonateStuNum()-subMember.getSub_donateStuNum());
			if(member.getDonateStuNum()<0){
				member.setDonateStuNum(0);
			}
			member.setMemberType(getMemberType(member.getDonateStuNum()));
			getMemberService().modifyMember(member);
			List<SubMember> oldSubMembers = memberExtService.getSubMembersByMember(member.getId());
			for (SubMember sMember : oldSubMembers) {
				sMember.setSub_memberType(member.getMemberType());
				getSubMemberService().modifySubMember(sMember);
			}
		}
		recache();
		return SUCCESS;
	}

	public String saveMESubMember() throws Exception {
		//TODO 同一事务
		//判断输入是否合法
		checkMEInputValue(getSubMember(),memberEnjoyId);
		getSubMember().setSub_createDate(new Date());
		User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		getSubMember().setSub_user(user);
		
		getSubMember().setSub_memberType(getMemberType(getSubMember().getSub_donateStuNum()));
		String type = addMember(getSubMember());
		getSubMember().setSub_memberType(type);
		MemberEnjoyActivity meActivity = new MemberEnjoyActivity();
		meActivity.setId(Integer.parseInt(memberEnjoyId));
		getSubMember().setSub_memberEnjoyActivity(meActivity);
		getSubMemberService().addSubMember(getSubMember());
		recache();
		return SUCCESS;
	}
	
	

	@Override
	public String addMember(SubMember subMember) throws Exception {
		Member member = null;
		if(subMember.getSub_cellPhone()!=null && subMember.getSub_cellPhone().length()!=0){
			member = getMemberService().getMember(2,subMember.getSub_cellPhone());
			if(member != null && !member.getMemberName().equals(subMember.getSub_memberName())){
				throw new Exception("手机号码已经被其他会员使用，请更换手机号码！");
			}
		}else if(subMember.getSub_idCard()!=null && subMember.getSub_idCard().length()!=0){
			member = getMemberService().getMember(1,subMember.getSub_idCard());
		}else{
			return subMember.getSub_memberType();
		}
		if(member == null){
			member = new Member();
			member.setBirthday(subMember.getSub_birthday());
			member.setCarBrand(subMember.getSub_carBrand());
			member.setCarType(subMember.getSub_carType());
			member.setCellPhone(subMember.getSub_cellPhone());
			member.setCreateDate(subMember.getSub_createDate());
			member.setDonateRecord(subMember.getSub_donateRecord());
			member.setDonateStuNum(subMember.getSub_donateStuNum());
			member.setEmail(subMember.getSub_email());
			member.setForumPosting(subMember.getSub_forumPosting());
			member.setGender(subMember.getSub_gender());
			member.setIdCard(subMember.getSub_idCard());
			member.setMemberName(subMember.getSub_memberName());
			member.setMemberType(subMember.getSub_memberType());
			member.setSubCompany(subMember.getSubCompany());
			member.setSubCity(subMember.getSubCity());
			member.setSubComName(subMember.getSubComName());
			member.setSubCityName(subMember.getSubCityName());
			member.setRemark(subMember.getSub_remark());
			member.setReproduceIntroduce(subMember.getSub_reproduceIntroduce());
			member.setUser(subMember.getSub_user());
			getMemberService().addMember(member);
		}else{
			member.setDonateStuNum(member.getDonateStuNum()+subMember.getSub_donateStuNum());
            member.setMemberType(getMemberType(member.getDonateStuNum()));	
            if(!(member.getCellPhone()!=null && member.getCellPhone().length()!=0)){
            	member.setCellPhone(subMember.getSub_cellPhone());
            }
            if(!(member.getBirthday()!=null && member.getBirthday().length()!=0)){
            	member.setBirthday(subMember.getSub_birthday());
            }
            if(!(member.getIdCard()!=null && member.getIdCard().length()!=0)){
            	member.setIdCard(subMember.getSub_idCard());
            }
            if(!(member.getEmail()!=null && member.getEmail().length()!=0)){
            	member.setEmail(subMember.getSub_email());
            }
            getMemberService().modifyMember(member);
            List<SubMember> oldSubMembers = memberExtService.getSubMembersByMember(member.getId());
			for (SubMember sMember : oldSubMembers) {
				sMember.setSub_memberType(member.getMemberType());
				getSubMemberService().modifySubMember(sMember);
			}
		}
		subMember.setMember(member);
		return member.getMemberType();
	}

	public String toSaveMESubMember(){
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		MemberEnjoyActivity meActivity = memberEnjoyService.findMemberEnjoyActivity(Integer.parseInt(memberEnjoyId));
		if(getSubMember() ==null){
			this.setSubMember(new SubMember());
		}
		getSubMember().setSubCompany(meActivity.getSubCompany());
		getSubMember().setSubCity(meActivity.getSubCity());
		getSubMember().setSubComName(meActivity.getSubComName());
		getSubMember().setSubCityName(meActivity.getSubCityName());
		httpServletRequest.setAttribute("memberEnjoyId", httpServletRequest.getParameter("memberEnjoyId"));
		return SUCCESS;
		
	}

	public String searchMESubMembers(){

		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		SubMemberVO subMemberVO = new SubMemberVO();
		String roleName = (String)session.get("rolename");
		User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		subMemberVO.setSubMember(getSubMember());
		subMemberVO.setRoleName(roleName);
		subMemberVO.setUser(user);
		subMemberVO.setStartbirthday(getStartbirthday());
		subMemberVO.setEndbirthday(getEndbirthday());
		subMemberVO.setStartcreate(getStartcreate());
		subMemberVO.setEndcreate(getEndcreate());
		subMemberVO.setMemberEnjoyId(memberEnjoyId);
		httpServletRequest.setAttribute("startcreate", getStartcreate());
		httpServletRequest.setAttribute("endcreate", getEndcreate());
		PagerModel pm = memberExtService.getSubMembers(subMemberVO, curPage);
		httpServletRequest.setAttribute("pm",pm);
		httpServletRequest.setAttribute("roleName", roleName);
		if(getSubMember() ==null){
			this.setSubMember(new SubMember());
		}
		MemberEnjoyActivity meActivity = memberEnjoyService.findMemberEnjoyActivity(Integer.parseInt(memberEnjoyId));
		getSubMember().setSubCompany(meActivity.getSubCompany());
		getSubMember().setSubCity(meActivity.getSubCity());
		getSubMember().setSubComName(meActivity.getSubComName());
		getSubMember().setSubCityName(meActivity.getSubCityName());
		httpServletRequest.setAttribute("memberEnjoyId", Integer.parseInt(memberEnjoyId));
		
		return SUCCESS;
	
	}
	
	
	private void checkMEInputValue(SubMember subMember,String journeyLoveId) throws Exception{
		if(subMember == null){
			throw new Exception("传入参数丢失请重新提交！");
		}else if(subMember.getSub_memberName() == null || subMember.getSub_memberName().length() == 0){
			throw new Exception("会员姓名不能为空！");
		}else if(subMember.getSub_gender() == null || subMember.getSub_gender().length() == 0){
			throw new Exception("会员性别不能为空！");
		}else if(subMember.getSub_cellPhone() == null || subMember.getSub_cellPhone().length() == 0){
			throw new Exception("会员手机号码不能为空！");
		}else if(!checkPhone(subMember.getSub_cellPhone())){
			throw new Exception("会员手机号码格式错误！");
		}else if(subMember.getSub_donateRecord() == null || subMember.getSub_donateRecord().length() == 0){
			throw new Exception("会员捐赠记录不能为空！");
		}else if(subMember.getSub_donateStuNum() == null || subMember.getSub_donateStuNum().toString().length() == 0){
			subMember.setSub_donateStuNum(0);
		}else if(!checkSub_donateStuNum(String.valueOf(subMember.getSub_donateStuNum()))){
			throw new Exception("捐助学生数必须为0和正整数！");
		}
		if(memberExtService.getMemberEnjoySubMemberByPhone(subMember.getSub_cellPhone(), memberEnjoyId) != null){
			throw new Exception("会员手机号码已经被其他会员使用，请更换手机号码！");
		}
	}
	
	private boolean isJourneyOfLovePage(){
		return StringUtils.isBlank(memberEnjoyId);
	}
	
	
	
}
